package pa165.dominatingspecies.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import pa165.dominating.species.dao.UserDAO;
import pa165.dominating.species.entities.User;
import pa165.dominating.species.service.UserService;
import pa165.dominatingspecies.service.converter.UserConverter;
import pa165.dominating.species.tos.UserTO;

/**
 * @author Tomas Kalla
 */
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private UserConverter userConverter;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @PreAuthorize("hasRole('ADMIN')")
    public void createUser(final UserTO userTO) {
        User user = userConverter.convertUserTO2User(userTO);
        userDAO.createUser(user);

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @PreAuthorize("hasRole('ADMIN')")
    public void updateUser(final UserTO userTO) {
        User user = userConverter.convertUserTO2User(userTO);
        userDAO.updateUser(user);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @PreAuthorize("hasRole('ADMIN')")
    public void deleteUser(final UserTO userTO) {
        User user = userConverter.convertUserTO2User(userTO);
        userDAO.deleteUser(user);
    }

    @Override
    @PreAuthorize("hasRole('WORKER')")
    public UserTO getUserById(final Long id) {
        User user = userDAO.getUserById(id);
        return userConverter.convertUser2UserTO(user);
    }

    @Override
    public UserTO getUserByUserName(String username) {
        User user = userDAO.getUserByUserName(username);
        return userConverter.convertUser2UserTO(user);
    }

    @Override
    @PreAuthorize("hasRole('WORKER')")
    public List<UserTO> getAllUsers() {
        List<User> users = userDAO.getAllUsers();
        List<UserTO> usersResult = new ArrayList<>();
        for (User user : users) {
            usersResult.add(userConverter.convertUser2UserTO(user));
        }
        return usersResult;
    }
}
